package com.example.zhaojianxu.signin.signIn.teacher.view

import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProviders
import android.os.Bundle
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.zhaojianxu.signin.R
import com.example.zhaojianxu.signin.common.bean.BaseFragment
import com.example.zhaojianxu.signin.signIn.teacher.adapter.TeacherAdapter
import com.example.zhaojianxu.signin.signIn.teacher.model.TeacherEntity
import com.example.zhaojianxu.signin.signIn.teacher.viewModel.TeacherViewModel
import kotlinx.android.synthetic.main.fragment_teacher.*

class TeacherFragment: BaseFragment(), SwipeRefreshLayout.OnRefreshListener {

    var mView: View? = null
    lateinit var mViewModel: TeacherViewModel
    lateinit var mAdapter: TeacherAdapter
    var mList: MutableList<TeacherEntity> = mutableListOf()

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {

        mView = inflater.inflate(R.layout.fragment_teacher,container,false)
        return mView
    }

    override fun initView() {
        teacher_swipe_refresh.setOnRefreshListener(this)

        teacher_recycler.layoutManager = LinearLayoutManager(this.context)
    }

    override fun initData() {
        mViewModel = ViewModelProviders.of(this)[TeacherViewModel::class.java]
        mAdapter = TeacherAdapter(mList)

        teacher_recycler.adapter = mAdapter

        mViewModel.teacher.observe(this, Observer {
            mList.clear()
            it?.forEach {
                mList.add(it)
            }
            teacher_swipe_refresh.isRefreshing = false
            mAdapter.notifyDataSetChanged()
        })
    }

    override fun onRefresh() {
        mViewModel.refresh()
    }

    override fun onResume() {
        super.onResume()
        mViewModel.refresh()
    }
}